#!/bin/bash
# File Name: monitor_zabbix.sh
# Author: moshan
# mail: mo_shan@yeah.net
# Created Time: 2019-04-09 12:16:33
# Function: 
#########################################################################
table_name="dba_test"
db_name="test"
mysql_host="192.168.1.157"
mysql_port="3307"
mysql_user="moshan"
mysql_password="xxxxxxxxxxxxx"
log_dir="log"
log_file_ok="${log_dir}/ok.log"
log_file_error="${log_dir}/error.log"
mysql_comm="mysql -u${mysql_user} -p${mysql_password} -P${mysql_port} -h${mysql_host}"
id=1
w_stat=0
${mysql_comm} ${db_name} -e "delete from ${table_name};" 2>/dev/null
function send_info()
{
	tail -1 ${log_file_error} > send.log
	python3 send.py send.log "zabbix 写入异常" >/dev/null
}
while :
do
    t_time="$(date "+%s")"
    insert_sql="insert into ${table_name} select ${id},${t_time};"
    ${mysql_comm} ${db_name} -e "${insert_sql};" 2>/dev/null
    new_t_time="$(${mysql_comm} ${db_name} -NBe "select t_time from ${table_name} where t_time=${t_time}" 2>/dev/null)"
    took_time="$(($(date "+%s")-${t_time}))"
    if [ "${t_time}x" == "${new_t_time}x" ]
    then
        w_stat=0
    else
        w_stat=1
    fi
    if [ ${took_time} -le 2 ]
    then
        t_stat=0
    else
        t_stat=1
    fi
    if [ "${w_stat}x" == "0x" -a "${t_stat}x" == "0x" ]
    then
        echo -e "\033[32m[$(date "+%F %H:%M:%S")] [ok] [${insert_sql}] [Successfully written!]" >> ${log_file_ok}
    elif [ "${w_stat}x" == "0x" -a "${t_stat}x" == "1x" ]
    then
        echo -e "\033[33m[$(date "+%F %H:%M:%S")] [ERROR] [${insert_sql}] [Successfully written!] [But, this write took ${took_time} second] " >> ${log_file_error}
        send_info
    elif [ "${w_stat}x" == "1x" -a "${t_stat}x" == "0x" ]
    then
        echo -e "\033[33m[$(date "+%F %H:%M:%S")] [ERROR] [${insert_sql}] [Write failure!]" >> ${log_file_error}
        send_info
    fi
    sleep 1
    id=$((${id}+1))
done
